﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;

// SyncVar特性
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class SyncVarAttribute : Attribute
{
    public bool SendOnChange { get; set; } = true;

    public SyncVarAttribute() { }
}

public class NetworkBehaviour : MonoBehaviour
{
    [Header("网络属性")]
    public bool isLocalPlayer = false;
    public string networkId = "";
    public string ownerId = "";

    [Header("同步设置")]
    [Range(1, 30)]
    public int syncRate = 10;
    public bool autoSync = true;

    // 内部变量
    private NetworkManager networkManager;
    private Dictionary<FieldInfo, object> syncVarFields = new Dictionary<FieldInfo, object>();
    private Dictionary<FieldInfo, object> lastValues = new Dictionary<FieldInfo, object>();
    private float syncInterval;
    private bool hasInitialized = false;

    protected virtual void Start()
    {
        // 获取NetworkManager引用
        networkManager = FindObjectOfType<NetworkManager>();
        if (networkManager == null)
        {
            Debug.LogError("未找到NetworkManager！");
            return;
        }

        syncInterval = 1f / syncRate;

        // 初始化SyncVar
        InitializeSyncVars();

        // 注册到NetworkManager
        networkManager.RegisterNetworkBehaviour(this);

        hasInitialized = true;

        if (autoSync && isLocalPlayer)
        {
            StartCoroutine(SyncCoroutine());
        }
    }

    void InitializeSyncVars()
    {
        var type = GetType();
        var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        foreach (var field in fields)
        {
            if (field.GetCustomAttribute<SyncVarAttribute>() != null)
            {
                syncVarFields[field] = field.GetValue(this);
                lastValues[field] = field.GetValue(this);

                Debug.Log($"发现SyncVar字段: {field.Name} = {field.GetValue(this)}");
            }
        }
    }

    IEnumerator SyncCoroutine()
    {
        while (isLocalPlayer && networkManager != null && networkManager.isConnected)
        {
            yield return new WaitForSeconds(syncInterval);

            if (HasSyncVarChanges())
            {
                    SendSyncVarUpdates();
            }
        }
    }

    bool HasSyncVarChanges()
    {
        foreach (var field in syncVarFields.Keys.ToList())
        {
            var currentValue = field.GetValue(this);
            var lastValue = lastValues[field];

            if (!ValuesAreEqual(currentValue, lastValue))
            {
                return true;
            }
        }
        return false;
    }

    void SendSyncVarUpdates()
    {
        if (networkManager == null || !isLocalPlayer) return;

        // 验证 networkId 不为空
        if (string.IsNullOrEmpty(networkId))
        {
            Debug.LogError($"NetworkBehaviour {gameObject.name} 的 networkId 为空，无法发送SyncVar更新");
            return;
        }

        var updates = new Dictionary<string, SyncVarValue>();

        foreach (var field in syncVarFields.Keys.ToList())
        {
            var currentValue = field.GetValue(this);
            var lastValue = lastValues[field];

            if (!ValuesAreEqual(currentValue, lastValue))
            {
                var syncVarValue = new SyncVarValue(currentValue);
                updates[field.Name] = syncVarValue;
                lastValues[field] = currentValue;

                Debug.Log($"SyncVar变化: {field.Name} = {currentValue} (NetworkId: {networkId})");
            }
        }

        if (updates.Count > 0)
        {
            Debug.Log($"发送 {updates.Count} 个SyncVar更新，NetworkId: {networkId}");
            networkManager.SendSyncVarUpdate(networkId, updates);
        }
    }

    public void ApplySyncVarUpdate(string fieldName, SyncVarValue value)
    {
        Debug.Log($"ApplySyncVarUpdate被调用: {fieldName} = {value.Value} (对象: {gameObject.name}, IsLocal: {isLocalPlayer})");
        
        if (isLocalPlayer) 
        {
            return; // 本地玩家不接收更新
        }

        var field = syncVarFields.Keys.FirstOrDefault(f => f.Name == fieldName);
        if (field != null)
        {
            try
            {
                var convertedValue = ConvertStringToValue(value.Value, field.FieldType);
                var oldValue = field.GetValue(this);
                
                field.SetValue(this, convertedValue);
                lastValues[field] = convertedValue;

                Debug.Log($"SyncVar更新成功: {fieldName} 从 {oldValue} 更新为 {convertedValue} (对象: {gameObject.name})");
                
                // 特别记录位置更新
                if (fieldName == "targetPosition" && this is PlayerInfo)
                {
                    Debug.Log($"玩家位置已更新: {gameObject.name} -> {convertedValue}");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"应用SyncVar更新失败: {fieldName} = {value.Value}");
                Debug.LogError($"错误: {ex.Message}");
                Debug.LogError($"堆栈: {ex.StackTrace}");
            }
        }
        else
        {
            Debug.LogWarning($"未找到SyncVar字段: {fieldName} (对象: {gameObject.name})");
            Debug.Log($"可用的SyncVar字段:");
            foreach (var syncField in syncVarFields.Keys)
            {
                Debug.Log($"  - {syncField.Name}");
            }
        }
    }

    object ConvertStringToValue(string value, Type targetType)
    {
        if (string.IsNullOrEmpty(value)) return null;

        if (targetType == typeof(string))
            return value;
        else if (targetType == typeof(int))
            return int.Parse(value);
        else if (targetType == typeof(float))
            return float.Parse(value);
        else if (targetType == typeof(bool))
            return bool.Parse(value);
        else if (targetType == typeof(Vector3))
        {
            var parts = value.Split(',');
            if (parts.Length == 3)
            {
                return new Vector3(
                    float.Parse(parts[0]),
                    float.Parse(parts[1]),
                    float.Parse(parts[2])
                );
            }
        }

        return null;
    }

    bool ValuesAreEqual(object value1, object value2)
    {
        if (value1 == null && value2 == null) return true;
        if (value1 == null || value2 == null) return false;
        return value1.Equals(value2);
    }

    // 设置网络身份
    public void SetNetworkIdentity(string id, string owner, bool isLocal)
    {
        networkId = id;
        ownerId = owner;
        isLocalPlayer = isLocal;

        Debug.Log($"设置网络身份: ID={id}, Owner={owner}, IsLocal={isLocal}");

        if (hasInitialized && autoSync && isLocalPlayer)
        {
            Debug.Log($"启动自动同步协程 for {gameObject.name}");
            StartCoroutine(SyncCoroutine());
        }
    }

    public string GetNetworkId() => networkId;
    public string GetOwnerId() => ownerId;
    public bool IsLocalPlayer() => isLocalPlayer;

    protected virtual void OnDestroy()
    {
        if (networkManager != null)
        {
            networkManager.UnregisterNetworkBehaviour(this);
        }
        StopAllCoroutines();
    }
}